<template>
    <div>
        <quill-editor style="height: 300px" v-model="content"
                      ref="myQuillEditor"
                      :options="editorOption"
                      @change="onEditorChange($event)">
            >
        </quill-editor>
        <div style="display:none;">
            <a-upload
                    name="file"
                    listType="picture-card"
                    class="avatar-uploader"
                    :showUploadList="false"
                    :customRequest="customRequest"
            >
                <div ref="quillUpload">
                    <a-icon type="plus"/>
                    <div class="ant-upload-text">Upload</div>
                </div>
            </a-upload>
        </div>
    </div>
</template>

<script>
    import HiddenUpLoad from "./upload/HiddenUpLoad";

    const toolbarOptions = [
        ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
        ["blockquote", "code-block"], // 引用  代码块
        [{header: 1}, {header: 2}], // 1、2 级标题
        [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表
        [{script: "sub"}, {script: "super"}], // 上标/下标
        [{indent: "-1"}, {indent: "+1"}], // 缩进
        // [{'direction': 'rtl'}],                         // 文本方向
        [{size: ["small", false, "large", "huge"]}], // 字体大小
        [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题
        [{color: []}, {background: []}], // 字体颜色、字体背景颜色
        [{font: []}], // 字体种类
        [{align: []}], // 对齐方式
        ["clean"], // 清除文本格式
        ["link", "image"] // 链接、图片、视频
    ];
    import {quillEditor, Quill} from 'vue-quill-editor'
    // import { ImageResize } from 'quill-image-resize-module';//调节图片大小

    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
    import uploadApi from "../api/upload";

    // Quill.register('modules/imageResize', ImageResize)


    export default {
        name: "MyQuillEditor",
        components: {HiddenUpLoad, quillEditor},

        props: {
            field: String,
            toRemoveIds: Array,
            content:String
        },
        data() {
            return {
                idnex: 0,
                editorOption: {},
                imgIds: [],//所有图片id
                removeIds: [],//被删除图片id
            }
        },
        created() {
            let vm = this
            let option = {
                theme: "snow", // or 'bubble'
                placeholder: "请输入内容",
                modules: {
                    /* ImageResize: {
                         displayStyles: {
                             backgroundColor: 'black',
                             border: 'none',
                             color: 'white'
                         },
                         modules: ['Resize', 'DisplaySize', 'Toolbar']
                     },*/
                    toolbar: {
                        container: toolbarOptions,
                        handlers: {
                            image: function (value) {
                                vm.$refs.quillUpload.click()//自定义图片上传回调
                            },

                        }
                    }
                }
            }
            vm.editorOption = option

        },
        methods: {

            onEditorChange({quill, html, text}) {
                this.$emit("getQuillContent", html, this.field)
                //获取当前富文本中所有的图片地址列表
                let newIds = this.matchImgSrc(html);
                console.log(newIds)
                if (newIds && newIds.length > 0) {
                    //获取旧列表中存在但新列表不存在的地址 为已经删除的图片地址
                    let removeIds = this.imgIds.filter(oldId => !newIds.some(newId => newId === oldId))
                    console.log(removeIds)
                    console.log(this.imgIds)
                    if (removeIds && removeIds.length > 0) {
                        this.removeIds = removeIds;
                        this.$emit("refreshRemoveImages", this.removeIds)
                    }
                    this.imgIds = newIds;
                } else {
                    console.log(this.imgIds)

                    this.removeIds = this.imgIds;
                    this.imgIds=[]
                    this.$emit("refreshRemoveImages", this.removeIds)
                }

            },
            matchImgSrc(content) {
                // 匹配src属性
                let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/gi

                let srcArr = content.match(srcReg)
                if (srcArr && srcArr.length > 0) {
                    let res = []
                    for (let i = 0; i < srcArr.length; i++) {
                        res.push(srcArr[i].substring(5, srcArr[i].length - 1))
                    }
                    return res

                } else {
                    return undefined;
                }


            },
            customRequest(data) {
                let formData = new FormData();
                formData.append("file", data.file);
                this.saveFile(formData, data.file.name);
            },

            saveFile(formData, filename) {

                  uploadApi
                      .uploadCommon(formData,3)
                      .then(resp => {
                          if (resp.data.flag) {
                              const file = {};
                              file.uid = -2;
                              file.name = filename;
                              file.thumbUrl = resp.data.data;
                              let quill = this.$refs.myQuillEditor.quill
                              let length = quill.getSelection().index　//获取当前鼠标焦点位置
                              quill.insertEmbed(length, 'image', file.thumbUrl)//插入<img src='url'/>
                              quill.setSelection(length + 1)  //鼠标焦点位置

                              this.$message.success("上传成功");
                          } else {
                              this.$message.error(resp.data.message);
                          }
                      })
                      .catch(error => {
                          console.log(error)
                          this.loading = false;

                          this.$message.error(error);
                      });
            },
        },

    }
</script>

<style scoped>

</style>